package org.jeecg.modules.demo.ch.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChDemandFeedback;
import org.jeecg.modules.demo.ch.entity.ChSysProblemAllocation;
import org.jeecg.modules.demo.ch.entity.RequirementComments;
import org.jeecg.modules.demo.ch.exception.Assert;
import org.jeecg.modules.demo.ch.exception.CustomException;
import org.jeecg.modules.demo.ch.service.IChDemandFeedbackService;
import org.jeecg.modules.demo.ch.service.IChSysProblemAllocationService;
import org.jeecg.modules.demo.ch.service.IRequirementCommentsService;
import org.jeecg.modules.demo.ch.vo.ChDemandFeedbackPage;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 需求反馈
 * @Author: jeecg-boot
 * @Date: 2022-11-15
 * @Version: V1.0
 */
@Api(tags = "需求反馈")
@RestController
@RequestMapping("/ch/chDemandFeedback")
@Slf4j
public class ChDemandFeedbackController {
    @Autowired
    private IChDemandFeedbackService chDemandFeedbackService;
    @Autowired
    private IRequirementCommentsService requirementCommentsService;

    @Autowired
    private IChSysProblemAllocationService chSysProblemAllocationService;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 获取所有的用户信息（下拉框）
     *
     * @return
     */
    @AutoLog(value = "获取所有的用户信息（下拉框）")
    @ApiOperation(value = "获取所有的用户信息（下拉框）", notes = "获取所有的用户信息（下拉框）")
    @PostMapping(value = "/getAllUser")
    public Result<List<LoginUser>> getAllUser(String userName) {
        List<LoginUser> allUser = sysUserService.getAllUser(userName);
        return Result.OK(allUser);
    }


    /**
     * 获取当前登录人以及根据当前username查找对应的部门(默认是登录人的部门)
     *
     * @return
     */
    @AutoLog(value = "需求反馈-获取当前登录人以及根据当前username查找对应的部门(默认是登录人的部门)")
    @ApiOperation(value = "需求反馈-获取当前登录人以及根据当前username查找对应的部门(默认是登录人的部门)", notes = "需求反馈-获取当前登录人以及根据当前username查找对应的部门(默认是登录人的部门)")
    @PostMapping(value = "/getDepartMentByUserName")
    public Result<Map<String, Object>> getDepartMentByUserName(String username) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String code = sysUser.getUsername();//登录人账号
        if (StringUtils.hasLength(username)) {
            code = username;
        }
        List<SysDepart> sysDeparts = sysDepartService.queryDepartsByUsername(code);
        List<String> departNames = sysDeparts.stream().map(SysDepart::getDepartName).distinct().collect(Collectors.toList());
        List<String> departIds = sysDeparts.stream().map(SysDepart::getId).distinct().collect(Collectors.toList());
        HashMap<String, Object> hashMap = new HashMap<>(3);
        hashMap.put("loginUser", sysUser);//登录人
        hashMap.put("departNames", String.join(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA, departNames));
        hashMap.put("departIds", String.join(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA, departIds));
        return Result.OK(hashMap);
    }


    /**
     * 分页列表查询
     *
     * @param chDemandFeedback
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "需求反馈-分页列表查询")
    @ApiOperation(value = "需求反馈-分页列表查询", notes = "需求反馈-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ChDemandFeedback>> queryPageList(ChDemandFeedback chDemandFeedback,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        log.info("传来的参数chDemandFeedback:{}", chDemandFeedback);
//		QueryWrapper<ChDemandFeedback> queryWrapper = QueryGenerator.initQueryWrapper(chDemandFeedback, req.getParameterMap());
        String belongSystem = chDemandFeedback.getBelongSystem();//所属系统
        String feedbackDepartment = chDemandFeedback.getFeedbackDepartment();//反馈部门
        String questioner = chDemandFeedback.getQuestioner();//提问人
        String problemType = chDemandFeedback.getProblemType();//问题类型
        String problemDesc = chDemandFeedback.getProblemDesc();//问题描述
        String assigner = chDemandFeedback.getAssigner();//指派人
        String status = chDemandFeedback.getStatus();
        String id = chDemandFeedback.getId();//主键id
        String feedbackDate_begin = chDemandFeedback.getFeedbackDate_begin() != null ? chDemandFeedback.getFeedbackDate_begin().toString() : null;
        String feedbackDate_end = chDemandFeedback.getFeedbackDate_end() != null ? chDemandFeedback.getFeedbackDate_end().toString() : null;

        if (feedbackDate_begin != null) {
            feedbackDate_begin = feedbackDate_begin.substring(1, 11);
        }
        if (feedbackDate_end != null) {
            feedbackDate_end = feedbackDate_end.substring(1, 11);
        }

        //结束日期+1天
        if (StringUtils.hasLength(feedbackDate_end)) {
            LocalDate date = LocalDate.parse(feedbackDate_end);
            LocalDate localDate = date.plusDays(1);
            DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonMst.WEEKLYREPORT.DATEFORMAT);
            feedbackDate_end = localDate.format(df);
        }

        LambdaQueryWrapper<ChDemandFeedback> feedbackLambdaQueryWrapper = new QueryWrapper<ChDemandFeedback>().lambda()
                .like(StringUtils.hasLength(belongSystem), ChDemandFeedback::getBelongSystem, belongSystem)
                .like(StringUtils.hasLength(feedbackDepartment), ChDemandFeedback::getFeedbackDepartment, feedbackDepartment)
                .like(StringUtils.hasLength(questioner), ChDemandFeedback::getQuestioner, questioner)
                .like(StringUtils.hasLength(problemType), ChDemandFeedback::getProblemType, problemType)
                .like(StringUtils.hasLength(problemDesc), ChDemandFeedback::getProblemDesc, problemDesc)
                .like(StringUtils.hasLength(status),ChDemandFeedback::getStatus,status)
                .like(StringUtils.hasLength(assigner),ChDemandFeedback::getAssigner,assigner)
                .eq(StringUtils.hasLength(id), ChDemandFeedback::getId, id)
                .ge(feedbackDate_begin != null, ChDemandFeedback::getFeedbackDate, feedbackDate_begin)
                .le(feedbackDate_end != null, ChDemandFeedback::getFeedbackDate, feedbackDate_end);
        Page<ChDemandFeedback> page = new Page<ChDemandFeedback>(pageNo, pageSize);
        IPage<ChDemandFeedback> pageList = chDemandFeedbackService.page(page, feedbackLambdaQueryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 获取指派人
     *
     * @param chDemandFeedback
     * @return
     */
    public String getDefaultAssigner(ChDemandFeedback chDemandFeedback) {
        String assigner = chDemandFeedback.getAssigner();//指派人
        String assignerRealNames="";//定义返回的指派者realName  多个人逗号拼接
        if (!StringUtils.hasLength(assigner)) {
            //根据系统名称和问题类型获取默认指派人
            String belongSystem = chDemandFeedback.getBelongSystem();//所属系统
            String problemType = chDemandFeedback.getProblemType();
            LambdaQueryWrapper<ChSysProblemAllocation> allocationLambdaQueryWrapper = new QueryWrapper<ChSysProblemAllocation>().lambda()
                    .eq(ChSysProblemAllocation::getSystemName, belongSystem)
                    .eq(ChSysProblemAllocation::getProblemType, problemType);
            List<ChSysProblemAllocation> list = chSysProblemAllocationService.list(allocationLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                assigner = list.get(0).getAllocator();
            }else {
                throw  new RuntimeException("根据所属系统:"+belongSystem+"问题类型:"+problemType+"未找到默认指派人，请先进行维护!");
            }

            if (!StringUtils.hasLength(assigner)){
                throw  new RuntimeException("根据所属系统:"+belongSystem+"问题类型:"+problemType+"未找到默认指派人，请先进行维护!");
            }
            if (assigner.contains(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA)){
                StringBuilder sb = new StringBuilder();
                String[] split = assigner.split(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA);
                for (String username : split) {
                    //根据username 获取realName
                    String realName = getRealNameByUserName(username);
                    sb.append(realName).append(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA);
                }
                //去除拼接的最后一个逗号
                if (sb.length() > 0) {
                    assignerRealNames = sb.substring(0, sb.length() - 1);
                }
            }else {
                String realName = getRealNameByUserName(assigner);//根据userName获取RealName
                assignerRealNames=realName;
            }
        }else {
            assignerRealNames=assigner;
        }
        return assignerRealNames;
    }

    /**
     * 根据userName获取RealName
     * @param userName
     */
    public String getRealNameByUserName(String userName){
        //根据username 获取realName
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getUsername,userName);
        List<SysUser> sysUserList = sysUserService.list(userLambdaQueryWrapper);
        String realname =sysUserList.get(0).getRealname();
        return  realname;
    }

    /**
     * 发送系统消息
     *
     * @param chDemandFeedback
     */
    public void sendSystemMsg(ChDemandFeedback chDemandFeedback) {
        //发送系统通知
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("belongSystem", chDemandFeedback.getBelongSystem());
        templateParam.put("questioner", chDemandFeedback.getQuestioner());
        templateParam.put("problemType", chDemandFeedback.getProblemType());
        templateParam.put("problemDesc", chDemandFeedback.getProblemDesc());
        templateParam.put("taskId",chDemandFeedback.getId());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//当前登录人
        String questioner = chDemandFeedback.getQuestioner();//提问人
        String status = chDemandFeedback.getStatus(); //3.已完成4.关闭  情况下不用通知提问人
        //根据指派人发送消息
        String assigner = chDemandFeedback.getAssigner();
        if (assigner.contains(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA)) {
            String[] split = assigner.split(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA);
            for (String realName : split) {
                //状态为已完成或者关闭  并且 指派人为提问人不进行发送消息通知
                if (StringUtils.hasLength(status) && (status.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_3 ) || status.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_4)) && realName.equals(questioner)){
                    continue;
                }
                sendTemplateAnnouncement(realName,sysUser,templateParam);
            }
        } else {
            //状态为已完成或者关闭  并且 指派人为提问人不进行发送消息通知 （因为只有提问人才会修改状态为已完成或关闭）
            if (StringUtils.hasLength(status) && (status.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_3 ) || status.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_4)) && assigner.equals(questioner)){
                return;
            }
            sendTemplateAnnouncement(assigner,sysUser,templateParam);
        }
    }

    /**
     * @param assigner
     * @param sysUser
     * @param templateParam
     */
    public void sendTemplateAnnouncement(String assigner, LoginUser sysUser,Map<String, String> templateParam){
        //根据realName获取userName
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getRealname,assigner);
        List<SysUser> sysUserList = sysUserService.list(userLambdaQueryWrapper);
        String userName =sysUserList.get(0).getUsername();
        TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO(sysUser.getUsername(), userName, CommonMst.DEMAND_FEEDBACK_SYSTEM.TITLE, templateParam, CommonMst.DEMAND_FEEDBACK_SYSTEM.TEMPLATE_CODE);
        iSysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
    }

    /**
     * 添加
     *
     * @param chDemandFeedbackPage
     * @return
     */
    @AutoLog(value = "需求反馈-添加")
    @ApiOperation(value = "需求反馈-添加", notes = "需求反馈-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ChDemandFeedbackPage chDemandFeedbackPage) {
        log.info("传入的参数chDemandFeedbackPage:{}",chDemandFeedbackPage);
        try {
            ChDemandFeedback chDemandFeedback = new ChDemandFeedback();
            BeanUtils.copyProperties(chDemandFeedbackPage, chDemandFeedback);
            //数据非空校验
            Assert.validateEntity(chDemandFeedback);
            //获取指派人
            String defaultAssigner = getDefaultAssigner(chDemandFeedback);
            chDemandFeedback.setAssigner(defaultAssigner);
            chDemandFeedback.setFeedbackDate(new Date());//当前日期
            String status = chDemandFeedback.getStatus();
            if (!StringUtils.hasLength(status)){
               chDemandFeedback.setStatus(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_1);//未开始
            }
            chDemandFeedbackService.saveMain(chDemandFeedback, chDemandFeedbackPage.getRequirementCommentsList());
            //发送系统消息（添加的时候，只给指派人发送消息）
            sendSystemMsg(chDemandFeedback);
            return Result.OK("添加成功！");
        } catch (CustomException e) {
            e.printStackTrace();
            log.error("数据校验异常", e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 批量修改反馈状态
     * 反馈状态(1.未开始2.进行中3.已完成4.关闭)
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "需求反馈-批量修改反馈状态")
    @ApiOperation(value = "需求反馈-批量修改反馈状态", notes = "需求反馈-批量修改反馈状态")
    @RequestMapping(value = "/editStatusBatch", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editStatusBatch(@RequestParam(name = "ids", required = true) String ids, String status) {
        List<String> idList = Arrays.asList(ids.split(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA));
        for (String id : idList) {
            LambdaUpdateWrapper<ChDemandFeedback> chDemandFeedbackLambdaUpdateWrapper = new UpdateWrapper<ChDemandFeedback>().lambda()
                    .set(ChDemandFeedback::getStatus, status)
                    .eq(ChDemandFeedback::getId, id);
            this.chDemandFeedbackService.update(chDemandFeedbackLambdaUpdateWrapper);
        }
        return Result.OK("批量修改反馈状态成功！");
    }

    /**
     * 编辑
     *
     * @param chDemandFeedbackPage
     * @return
     */
    @AutoLog(value = "需求反馈-编辑")
    @ApiOperation(value = "需求反馈-编辑", notes = "需求反馈-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ChDemandFeedbackPage chDemandFeedbackPage) {
        try {
            ChDemandFeedback chDemandFeedback = new ChDemandFeedback();
            BeanUtils.copyProperties(chDemandFeedbackPage, chDemandFeedback);
            //数据非空校验
            Assert.validateEntity(chDemandFeedback);
            ChDemandFeedback chDemandFeedbackEntity = chDemandFeedbackService.getById(chDemandFeedback.getId());
            if (chDemandFeedbackEntity == null) {
                return Result.error("未找到对应数据");
            }
            //获取更新之前 数据库子表的size
            LambdaQueryWrapper<RequirementComments> requirementCommentsLambdaOldQueryWrapper = new QueryWrapper<RequirementComments>().lambda()
                    .eq(RequirementComments::getChDemandFeedbackId, chDemandFeedback.getId());
            List<RequirementComments> requirementCommentsOldList = requirementCommentsService.list(requirementCommentsLambdaOldQueryWrapper);

            chDemandFeedbackService.updateMain(chDemandFeedback, chDemandFeedbackPage.getRequirementCommentsList());
            //TODO:系统通知的逻辑  暂定评论表上的所有人都通知（点击已完成  不通知指派人）
            LambdaQueryWrapper<RequirementComments> requirementCommentsLambdaQueryWrapper = new QueryWrapper<RequirementComments>().lambda()
                    .eq(RequirementComments::getChDemandFeedbackId, chDemandFeedback.getId());
            List<RequirementComments> requirementCommentsList = requirementCommentsService.list(requirementCommentsLambdaQueryWrapper);
            String oldAssigner = chDemandFeedback.getAssigner();//最开始主表的指派人
            String questioner = chDemandFeedback.getQuestioner();//提问人
            String solution = chDemandFeedback.getSolution();//解决方案
            String status = chDemandFeedback.getStatus();//状态
            log.info("最开始主表的指派人oldAssigner:{}状态status:{}提问人questioner:{}solution:{}",oldAssigner,status,questioner,solution);
            if (CollectionUtils.isEmpty(requirementCommentsList)){
                //此时只有主表  解决方案不为空. 就将提问人也加入通知(解决人编辑 通知提问人)
                if (StringUtils.hasLength(solution)){
                    chDemandFeedback.setAssigner(questioner);
                }
                //此时只有主表 状态为已完成或者已关闭的情况下 只通知指派人
                if (status.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_3) || status.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.STATUS_4)){
                    chDemandFeedback.setAssigner(oldAssigner);
                }
                sendSystemMsg(chDemandFeedback);
            }else {

                //对指派人进行去重
                HashSet<String> assignerSet = new HashSet<>();
                List<String> assigners = requirementCommentsList.stream().map(requirementComments -> requirementComments.getAssigner()).collect(Collectors.toList());
                assigners.add(chDemandFeedback.getAssigner());//加入主表的指派人
                if (!CollectionUtils.isEmpty(assigners)){
                    for (String assigner : assigners) {
                        if (StringUtils.hasLength(assigner)){
                            if (assigner.contains(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA)){
                                String[] split = assigner.split(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA);
                                for (String assignOne : split) {
                                    assignerSet.add(assignOne);
                                }
                            }else {
                                assignerSet.add(assigner);
                            }
                        }
                    }
                }

                //1判断子表是新增还是编辑
                //1.1根据传过来的数量与数据库数量进行对比判断新增还是编辑
                int oldSize = 0;
                if (!CollectionUtils.isEmpty(requirementCommentsOldList)){
                     oldSize = requirementCommentsOldList.size();
                }
                int newSize = requirementCommentsList.size();
                log.info("更新之前子表的oldSize:{}更新之后子表的newSize:{}",oldSize,newSize);

                if (oldSize == newSize){//对比之前已有的数据  判断是否增加了反馈内容  增加了 通知提问人
                    for (RequirementComments requirementComments : requirementCommentsOldList) {
                        String idOld = requirementComments.getId();//反馈id
                        String feedbackContentOld = StringUtils.hasLength(requirementComments.getFeedbackContent()) ? requirementComments.getFeedbackContent() : "";//反馈内容
                        for (RequirementComments comments : requirementCommentsList) {
                            String idNew = comments.getId();
                            String feedbackContentNew = StringUtils.hasLength(comments.getFeedbackContent()) ? comments.getFeedbackContent() : "";
                            if (idNew.equals(idOld) && !feedbackContentNew.equals(feedbackContentOld)){//发生了改动  通知提问人
                                assignerSet.add(chDemandFeedback.getQuestioner());//添加提问人
                                //排除当前指派人
                                String assigner = comments.getAssigner();
                                assignerSet.remove(assigner);
                            }
                        }
                    }
                }
                String join = String.join(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA, assignerSet);
                chDemandFeedback.setAssigner(join);
                sendSystemMsg(chDemandFeedback);//给所有人发送通知
                chDemandFeedback.setAssigner(oldAssigner);//恢复原来的指派人
            }
            return Result.OK("编辑成功!");
        } catch (CustomException e) {
            log.error("数据校验异常", e);
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "需求反馈-通过id删除")
    @ApiOperation(value = "需求反馈-通过id删除", notes = "需求反馈-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        chDemandFeedbackService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "需求反馈-批量删除")
    @ApiOperation(value = "需求反馈-批量删除", notes = "需求反馈-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.chDemandFeedbackService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "需求反馈-通过id查询")
    @ApiOperation(value = "需求反馈-通过id查询", notes = "需求反馈-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ChDemandFeedback> queryById(@RequestParam(name = "id", required = true) String id) {
        ChDemandFeedback chDemandFeedback = chDemandFeedbackService.getById(id);
        if (chDemandFeedback == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(chDemandFeedback);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "需求评论通过主表ID查询")
    @ApiOperation(value = "需求评论主表ID查询", notes = "需求评论-通主表ID查询")
    @GetMapping(value = "/queryRequirementCommentsByMainId")
    public Result<List<RequirementComments>> queryRequirementCommentsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<RequirementComments> requirementCommentsList = requirementCommentsService.selectByMainId(id);
        return Result.OK(requirementCommentsList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "需求反馈-通过id查询主表以及副表内容")
    @ApiOperation(value = "需求反馈-通过id查询主表以及副表内容", notes = "需求反馈-通过id查询主表以及副表内容")
    @GetMapping(value = "/queryAllById")
    public Result<ChDemandFeedbackPage> queryAllById(@RequestParam(name = "id", required = true) String id) {
        ChDemandFeedbackPage chDemandFeedbackPage = new ChDemandFeedbackPage();
        ChDemandFeedback chDemandFeedback = chDemandFeedbackService.getById(id);
        if (chDemandFeedback == null) {
            return Result.error("未找到对应数据");
        }
        //复制主表内容
        BeanUtils.copyProperties(chDemandFeedback,chDemandFeedbackPage);
        //存放子表内容
        List<RequirementComments> requirementCommentsList = requirementCommentsService.selectByMainId(id);
        chDemandFeedbackPage.setRequirementCommentsList(requirementCommentsList);
        return Result.OK(chDemandFeedbackPage);

    }

    /**
     * 导出excel
     *
     * @param request
     * @param chDemandFeedback
     */
    @RequestMapping(value = "/exportXls") //myExportXls
    public ModelAndView exportXls(HttpServletRequest request, ChDemandFeedback chDemandFeedback) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ChDemandFeedback> queryWrapper = QueryGenerator.initQueryWrapper(chDemandFeedback, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<ChDemandFeedback> chDemandFeedbackList = chDemandFeedbackService.list(queryWrapper);

        // Step.3 组装pageList
        List<ChDemandFeedbackPage> pageList = new ArrayList<ChDemandFeedbackPage>();
        for (ChDemandFeedback main : chDemandFeedbackList) {
            ChDemandFeedbackPage vo = new ChDemandFeedbackPage();
            BeanUtils.copyProperties(main, vo);
            List<RequirementComments> requirementCommentsList = requirementCommentsService.selectByMainId(main.getId());
            vo.setRequirementCommentsList(requirementCommentsList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "需求反馈列表");
        mv.addObject(NormalExcelConstants.CLASS, ChDemandFeedbackPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("需求反馈数据", "导出人:" + sysUser.getRealname(), "需求反馈"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }


    /**Ob
     * 导出excel
     *
     * @param request
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:exportXls")
    @RequestMapping(value = "/myExportXls")
    public void myExportXls(HttpServletRequest request, HttpServletResponse response) {

        try{
            // Step.1 组装查询条件查询数据
            ExcelReader reader = ExcelUtil.getReader("D:/昌红IT部/批量导入模板-精简版.xls");
            List<Map<String,Object>> readAll = reader.readAll();
            System.out.println("readAll = " + readAll);
            ArrayList<Address> addressList = new ArrayList<>();
            for (Map<String, Object> map : readAll) {
                String str =  map.get("收件人姓名") != null ? String.valueOf(map.get("收件人姓名")) : "";
                log.info("str{}",str);
                Address addressEntity = new Address();
                if (StringUtils.hasLength(str)){
                    int i = indexOfFirstDigit(str);
                    System.out.println("i = " + i);
                    if (str.length()>=i && i != -1){
                        String name = str.substring(0, i);//姓名
                        addressEntity.setName(name);
                    }else {
                        addressEntity.setName("");
                    }
                    if (str.length()>=i+11 && i != -1){
                        String telPhone = str.substring(i, i+11);
                        addressEntity.setTelPhone(telPhone);
                    }else {
                        addressEntity.setTelPhone("");
                    }
                    if (str.length()>=i+11 && i != -1){
                        String address = str.substring(i+11, str.length());
                        addressEntity.setAddress(address);
                    }else {
                        addressEntity.setAddress("");
                    }
                    addressList.add(addressEntity);
                }
            }
            System.out.println("addressList = " + addressList);
            // 通过工具类创建writer
            // createFile(new File(templatePath));
            ExcelWriter writer = ExcelUtil.getWriter(true);

            //自定义标题别名
            writer.addHeaderAlias("name", "姓名");
            writer.addHeaderAlias("telPhone", "电话号");
            writer.addHeaderAlias("address", "地址");

            // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
            writer.setOnlyAlias(true);

            //跳过当前行，既第一行，非必须，在此演示用
//            writer.passCurrentRow();
//            writer.passCurrentRow();
//            writer.passCurrentRow();
            // 合并单元格后的标题行，使用默认标题样式
//            writer.merge(7, "益模系统的BOM导入模版");
            // 一次性写出内容，使用默认样式，强制输出标题
			writer.write(addressList, true);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
            ServletOutputStream out=response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        }catch (Exception e){
            log.error("文件导出异常!",e);
            // return Result.error("文件导出异常!",e);
        }
    }
@Data
class Address{
      private String name;
      private String telPhone;
      private String address;
}

    public static void main(String[] args) {
        String str ="葛倩16776198066河南省宁陵";
        int i = indexOfFirstDigit(str);
        System.out.println("i = " + i);
        String name = str.substring(0, 2);//姓名
        System.out.println("name = " + name);
        String telPhone = str.substring(2, 13);
        System.out.println("telPhone = " + telPhone);
        String address = str.substring(13, str.length());
        System.out.println("address = " + address);

    }
    public static int indexOfFirstDigit(String str){
        for (int index = 0; index < str.length(); index++) {
            if (Character.isDigit(str.charAt(index))) {//check if the character is digit or not
                return index;//if yes return the index
            }
        }
        return -1;//If there are no digit then return -1 or a default result
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ChDemandFeedbackPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ChDemandFeedbackPage.class, params);
                for (ChDemandFeedbackPage page : list) {
                    ChDemandFeedback po = new ChDemandFeedback();
                    BeanUtils.copyProperties(page, po);
                    chDemandFeedbackService.saveMain(po, page.getRequirementCommentsList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
